#include "bicyclemangerwid.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "PlaceManger.h"
#include <QMessageBox>

BicycleMangerWid::BicycleMangerWid(QWidget *parent) : QWidget(parent)
{
    this->setWindowTitle("单车调度");
    resize(400,300);
    this->fromLab = new QLabel("起点",this);
    this->fromBox = new QComboBox(this);
    this->toLab = new QLabel("终点",this);
    this->toBox = new QComboBox(this);
    this->numLab = new QLabel("单车调度的数量",this);
    this->numEdit = new QLineEdit(this);
    numEdit->setPlaceholderText("输入的数字不要超过起点单车数量");
    this->confirm = new QPushButton("确定",this);

    QHBoxLayout *fromLayout = new QHBoxLayout();
    QHBoxLayout *toLayout = new QHBoxLayout();
    QHBoxLayout *numLayout = new QHBoxLayout();
    QVBoxLayout *vLayout = new QVBoxLayout(this);

    fromLayout->addWidget(fromLab);
    fromLayout->addWidget(fromBox);

    toLayout->addWidget(toLab);
    toLayout->addWidget(toBox);

    numLayout->addWidget(numLab);
    numLayout->addWidget(numEdit);

    vLayout->addLayout(fromLayout);
    vLayout->addLayout(toLayout);
    vLayout->addLayout(numLayout);
    vLayout->addWidget(confirm);
    ComboxInit();

    connect(this->confirm,&QPushButton::released,this,&BicycleMangerWid::ConfirmBtnPressed);
}

void BicycleMangerWid::ConfirmBtnPressed()
{
    MyTool tool;
    char fromName[50];
    char toName[50];
    strcpy(fromName,this->fromBox->currentText().toStdString().c_str());
    strcpy(toName,this->toBox->currentText().toStdString().c_str());
    if(strcmp(fromName,toName)==0)
    {
        QMessageBox::information(this,"error!","起点与终点的名称不能相同");
        return ;
    }
    if(!tool.isDigitStr(this->numEdit->text()))
    {
        QMessageBox::information(this,"error!","您输入的数据不合法！！");
        return ;
    }
    int num = this->numEdit->text().toInt();
    PlaceManger PM;

    Place start;
    start = PM.getPalceByName(fromName);
    if(start.getBicycleNum()<num)
    {
        QMessageBox::information(this,"error","起点单车数量不足");
        return ;
    }
    QString tips = QString("您确定从") + fromName + "调动" + QString::number(num) + "辆单车到" + toName + "吗？";
    int res = QMessageBox::information(this,"tips",tips,QMessageBox::Yes,QMessageBox::No);
    if(res==QMessageBox::Yes)
    {
        PM.Edit(fromName,-num);
        PM.Edit(toName,num);
        emit Edited();
        this->numEdit->setText("");
    }
}

void BicycleMangerWid::ComboxInit()
{
    PlaceManger PM;
    int length = 0;
    Place *places = PM.List(length);
    for(int i = 0;i<length;i++)
    {
        if(strcmp(places[i].getName(),"")==0)
            continue;
        fromBox->addItem(places[i].getName());
        toBox->addItem(places[i].getName());
    }
}
